package cn.jolyoulu.common.redis.lock;

import cn.jolyoulu.common.redis.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;
import java.util.UUID;

/**
 * @Author LuZhouJin
 * @Date 2023/5/31
 * 分布式锁切面
 */
@Slf4j
@Aspect
@Component
public class RedisLockAspect {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisLockRuleManager redisLockRuleManager;

    @Pointcut("@annotation(cn.jolyoulu.common.redis.lock.RedisLock)")
    public void lockPointCut() {
    }

    @Around("lockPointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        //获取到对应方法上的ReqRedisLock注解
        Class<?> targetClass = pjp.getTarget().getClass();
        String methodName = pjp.getSignature().getName();
        Class[] parameterTypes = ((MethodSignature) pjp.getSignature()).getParameterTypes();
        Method method = targetClass.getMethod(methodName, parameterTypes);
        RedisLock annotation = method.getAnnotation(RedisLock.class);
        Class<? extends RedisLockKeyRule> keyClass = annotation.ruleType();
        RedisLockKeyRule redisLockKeyRule = redisLockRuleManager.get(keyClass);
        //未找到实现，直接执行
        if (Objects.isNull(redisLockKeyRule)) {
            log.error("未找到{}的对应的实现", keyClass);
            return pjp.proceed();
            //找到实现类，加锁执行
        } else {
            String tag = UUID.randomUUID().toString();
            String lock = redisLockKeyRule.getKey(annotation.arg(), pjp.getArgs());
            //加锁
            boolean tryLock = redisUtils.tryLock(lock, tag, annotation.timeOut(), annotation.timeUnit());
            try {
                if (tryLock) {
                    return pjp.proceed();
                } else {
                    redisLockKeyRule.LockFailure(); //重复请求回调
                }
            } finally {
                if (tryLock) {
                    redisUtils.unLock(lock, tag);
                }
            }
        }
        return null;
    }
}
